package com.hsmpay.mobile.action.user;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.action.base.MobileBaseAction;
import com.hsmpay.mobile.pojo.user.SendmsgLog;
import com.hsmpay.mobile.service.user.SendmsgLogService;
import com.hsmpay.mobile.service.user.VerifiService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 验证 action
 *
 * @author 颜铃璋
 * @date 2013-1-28
 */
@Controller("verifiAction")
@Scope("prototype")
public class VerifiAction extends MobileBaseAction {
    private static final long serialVersionUID = -5850367982749551414L;
    private static Logger log = Logger.getLogger(VerifiAction.class);

    @Resource(name = "verifiService")
    private VerifiService<BasePojo, Long> verifiService;
    @Resource(name = "sendmsgLogService")
    private SendmsgLogService<SendmsgLog, Long> sendmsgLogService;
 

    private String mobile;
    private Integer codeType;
    private String muuid;//终端唯一 标识
    private String uuid;//终端唯一 标识

    /**
     * 注册时 获取手机验证码
     *
     * @return
     * @throws Exception
     */
    public String mobileCode() throws Exception {
        log.debug("--- mobileCode() start ---");
        roleId = Long.parseLong(getJsonString("roleId"));
        if (StringUtils.isNotEmpty(getJsonString("muuid")))
            muuid = getJsonString("muuid");
        if (StringUtils.isNotEmpty(getJsonString("uuid")))
            uuid = getJsonString("uuid");
        else
            uuid = muuid;
        if (StringUtils.isNotEmpty(getJsonString("userId")))
            userId = Long.parseLong(getJsonString("userId"));
        if (StringUtils.isNotEmpty(getJsonString("mobile")))
            mobile = getJsonString("mobile");
        if (StringUtils.isNotEmpty(getJsonString("codeType")))
            codeType = Integer.parseInt(getJsonString("codeType"));
        if (StringUtils.isNotEmpty(getJsonString("terminalTypeId")))
            terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));

        log.debug("uuid = " + uuid);
        log.debug("mobile = " + mobile);
        log.debug("codeType = " + codeType);
//        if (null == uuid) {
//            log.warn("发送手机验证码时, 传入参数uuid为空");
//            sendAppErrorMsg("6001", "uuid");
//            return null;
//        }
        if (null == mobile) {
            log.warn("发送手机验证码时, 传入参数mobile为空");
            sendAppErrorMsg("6001", "mobile");
            return null;
        }
        if (null == codeType) {
            log.warn("发送手机验证码时, 传入参数codeType为空");
            sendAppErrorMsg("6001", "codeType");
            return null;
        }
        if (1 != codeType && 4 != codeType) {
            if (null == userId) {
                log.warn("发送手机验证码时，传入的参数userId为空");
                sendAppErrorMsg("6001", "userId");
                return null;
            }
        }

        try {
            mobile = mobile.trim();
            Map<String, String> result = new LinkedHashMap<String, String>();

            String code = NumberUtil.getRegisterMobileCode();//"888888";

            SendmsgLog sendmsgLog = new SendmsgLog();
            sendmsgLog.setCode(code);
            sendmsgLog.setCreateDate(new Date());
            sendmsgLog.setCodeType(codeType);
            sendmsgLog.setMobile(mobile);
            sendmsgLog.setRoleId(roleId);
            sendmsgLog.setTerminalTypeId(terminalTypeId);
            sendmsgLog.setUserId(userId);
            sendmsgLog.setUuId(uuid);

            if (sendmsgLogService.isSendOn90s(uuid, terminalTypeId, roleId)) {
                log.warn("发送手机验证码时, 一个手机在90秒内只能发送一条信息");

                sendmsgLog.setStatus(3);//未发送
                sendmsgLog.setReqCode("6103");
                sendmsgLog.setReqMsg("一个手机在90秒内只能发送一条信息！");
                sendmsgLogService.insertEntity(sendmsgLog);

                sendAppErrorMsg("6103");
                return null;
            }
            if (sendmsgLogService.isExceed30(uuid, terminalTypeId, roleId)) {
                log.warn("发送手机验证码时, 一个手机一天内最多发送30条验证信息");

                sendmsgLog.setStatus(3);//未发送
                sendmsgLog.setReqCode("6104");
                sendmsgLog.setReqMsg("一个手机一天内最多发送30条验证信息！");
                sendmsgLogService.insertEntity(sendmsgLog);

                sendAppErrorMsg("6104");
                return null;
            }
            String content = "尊敬的客户您好,您的手机验证码为: [" + code + "],感谢您的支持！";
            switch (codeType) {
                case 1://注册
                    User user = new User();
                    user.setMobile(mobile);
                    user.setRoleId(roleId);
                    user.setTerminalTypeId(terminalTypeId);
                    user = userService.searchEntity(user);
                    if (null != user) {
                        log.warn("发送验证码时, 手机已经注册！");
                        sendAppErrorMsg("6003", mobile);
                        return null;
                    }
                    result = verifiService.sendMobileCode(mobile, code, sendmsgLog,content);
                    break;
                case 2: //绑定银行卡
                    result = verifiService.sendMobileCode(mobile, code, sendmsgLog,content);
                    break;
                case 3: //修改结算类型
                    result = verifiService.sendMobileCode(mobile, code, sendmsgLog,content);
                    break;
                case 4://找回密码
                    result = verifiService.sendMobileCode(mobile, code, sendmsgLog, content);
                    break;
                case 5://绑定信用卡 秒到功能
                	result = verifiService.sendMobileCode(mobile, code, sendmsgLog, content);
                	break;
                case 6:
                    result = verifiService.sendMobileCode(mobile, code, sendmsgLog, content);
            }
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- register() end ---");
        }
        return null;
    }

    /**
     * 检测验证  获取动态验证类型
     *
     * @return
     * @throws Exception
     */
    public String checkVerifi() throws Exception {
        log.debug("--- checkVerifi() start ---");
        if (StringUtils.isNotEmpty(getJsonString("muuid")))
            muuid = getJsonString("muuid");
        if (StringUtils.isNotEmpty(getJsonString("uuid")))
            uuid = getJsonString("uuid");
        else
            uuid = muuid;
        if (StringUtils.isNotEmpty(getJsonString("userId")))
            userId = Long.parseLong(getJsonString("userId"));
        if (StringUtils.isNotEmpty(getJsonString("codeType")))
            codeType = Integer.parseInt(getJsonString("codeType"));

        log.debug("uuid = " + uuid);
        log.debug("userId = " + userId);
        log.debug("codeType = " + codeType);
//        if (null == uuid) {
//            log.warn("发送手机验证码时, 传入参数uuid为空");
//            sendAppErrorMsg("6001", "uuid");
//            return null;
//        }
        if (null == codeType) {
            log.warn("发送手机验证码时, 传入参数codeType为空");
            sendAppErrorMsg("6001", "codeType");
            return null;
        }
        if (1 != codeType && 4 != codeType) {
            if (null == userId) {
                log.warn("发送手机验证码时，传入的参数userId为空");
                sendAppErrorMsg("6001", "userId");
                return null;
            }
        }
        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("reqCode", "0000");
            result.put("reqMsg", "检测验证成功！");
            result.put("verifiType", 1);
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- checkVerifi() end ---");
        }
        return null;
    }
    //共众号获取验证码
    public String  customerRegisterSendValiCode() throws Exception {
    	 JSONObject resultJson = new JSONObject();
    	 String mobile = getRequest().getParameter("mobile");
    	  if (null == mobile) {
              log.warn("发送手机验证码时, 传入参数mobile为空");
              sendWeChatErrorMsg("6001", "mobile");
              return null;
          }
    	  String activationCode = getRequest().getParameter("activationCode");
    	  if (null == activationCode) {
    		  log.warn("发送手机验证码时, 传入参数activationCode为空");
    		  sendWeChatErrorMsg("6001", "activationCode");
    		  return null;
    	  }
    	  String terminalTypeId = getRequest().getParameter("terminalTypeId");
    	  if (null == terminalTypeId) {
    		  log.warn("发送手机验证码时, 传入参数terminalTypeId为空");
    		  sendWeChatErrorMsg("6001", "terminalTypeId");
    		  return null;
    	  }
    	  
    	  // 判断是否已经注册过
    	  User user = new User();
          user.setMobile(mobile);
          user.setTerminalTypeId(Long.parseLong(terminalTypeId));
          user = userService.searchEntity(user);
          if(user != null  && (user.getDPIStatus() == 1 || user.getDPIStatus() == 2)){
            	  resultJson.put("code", 1);
            	  resultJson.put("msg", "您已经注册过微商商户!");
            	  sendWeChatMsg(resultJson.toString());
            	  return null;
              
          }else{
        	  //判断二维码是否被注册过
        	  User user1 = new User();
        	  user1.setActivationCode(activationCode);
        	  user1.setTerminalTypeId(Long.parseLong(terminalTypeId));
        	  user1 = userService.searchEntity(user1);
        	  if(user1 != null && !user1.getLoginName().equals(mobile)){
        		  resultJson.put("code", 1);
            	  resultJson.put("msg", "注册码已被使用!");
            	  sendWeChatMsg(resultJson.toString());
            	  return null;
        	  }
          }
         
    	  String code = NumberUtil.getRegisterMobileCode();//"888888";
    	  String content = "尊敬的客户您好,您的手机验证码为: [" + code + "],感谢您的支持！";
    	  SendmsgLog sendmsgLog = new SendmsgLog();
          sendmsgLog.setCode(code);
          sendmsgLog.setCreateDate(new Date());
          sendmsgLog.setCodeType(codeType);
          sendmsgLog.setMobile(mobile);
          sendmsgLog.setRoleId(roleId);
          sendmsgLog.setTerminalTypeId(Long.parseLong(terminalTypeId));
          sendmsgLog.setUserId(userId);
          sendmsgLog.setUuId(uuid);
         
    	  Map<String,String> result = verifiService.sendMobileCode(mobile, code, sendmsgLog, content);
    	  resultJson.put("code", result.get("reqCode").equals("0000")?"0" : result.get("reqCode"));
    	  resultJson.put("msg", result.get("reqMsg"));
     	  sendWeChatMsg(resultJson.toString());

    	return null;
    }
    //共众号获取验证码
    public String  customerRegisterValidatePhoneNo() throws Exception {
    	String mobile = getRequest().getParameter("mobile");
    	String valiCode = getRequest().getParameter("valiCode");
    	String customerId = getRequest().getParameter("customerId");
    	String terminalTypeId = getRequest().getParameter("terminalTypeId");
    	JSONObject result = new JSONObject();
    	if (null == mobile) {
    		log.warn("发送手机验证码时, 传入参数mobile为空");
    		sendWeChatErrorMsg("6001", "mobile");
    		return null;
    	}
    	
    	if (null == valiCode) {
    		log.warn("发送手机验证码时, 传入参数valiCode为空");
    		sendWeChatErrorMsg("6001", "valiCode");
    		return null;
    	}
    	if (null == terminalTypeId) {
    		log.warn("发送手机验证码时, 传入参数terminalTypeId为空");
    		sendWeChatErrorMsg("6001", "terminalTypeId");
    		return null;
    	}
    
    	//验证 手机验证码
        boolean verifi = verifiService.verifiCode(VerifiService.CODETYPE_REGISTER, 1, valiCode, mobile, null);
        if (!verifi) {
            log.warn("注册时, 验证失败！");
            result.put("code", "2");
        	result.put("msg", "验证码错误!");
        	sendWeChatMsg(result.toString());
            return null;
        }
    	// 再次判断是否已经注册  已注册跳转到 修改页面  code 1
        User user = new User();
        user.setMobile(mobile);
        user.setTerminalTypeId(Long.parseLong(terminalTypeId));
        user = userService.searchEntity(user);
        if(user != null){
         result.put("code", "0");
         result.put("msg", "");
      	 sendWeChatMsg(result.toString());
      	  return null;
        }

    	result.put("code", "0");
    	result.put("msg", "");
    	sendWeChatMsg(result.toString());
    	
    	return null;
    }
    public static void main(String args[]) {
        String a = "{\"reqCode\":\"0000\",\"reqMsg\":\"该用户已激活\",\"marhui\":\"{\\\"error\\\":\\\"-1\\\",\\\"msg\\\":\\\"该用户已激活\\\",\\\"realName\\\":\\\"\\\",\\\"p2p_account\\\":\\\"18510082588\\\",\\\"p2p_token\\\":\\\"FEB3C58643C203923d4b7177\\\"}\"}";
        JSONObject json = JSONObject.fromObject(a);
        System.out.println(json.get("marhui"));
        System.out.println(a.replaceAll("\\\\", ""));
    }


    // 贷款获取验证码
    public String  loanRegisterSendValiCode() throws Exception {
        JSONObject resultJson = new JSONObject();
        String mobile = getRequest().getParameter("mobile");
        if (null == mobile) {
            log.warn("发送手机验证码时, 传入参数mobile为空");
            sendWeChatErrorMsg("6001", "mobile");
            return null;
        }
        String code = NumberUtil.getRegisterMobileCode();//"888888";
        String content = "尊敬的客户您好,您的手机验证码为: [" + code + "],感谢您的支持！";
        SendmsgLog sendmsgLog = new SendmsgLog();
        sendmsgLog.setCode(code);
        sendmsgLog.setCreateDate(new Date());
        sendmsgLog.setCodeType(codeType);
        sendmsgLog.setMobile(mobile);
        sendmsgLog.setRoleId(roleId);
        //sendmsgLog.setTerminalTypeId(Long.parseLong(terminalTypeId));
        sendmsgLog.setUserId(userId);
        sendmsgLog.setUuId(uuid);

        Map<String,String> result = verifiService.sendMobileCode(mobile, code, sendmsgLog, content);
        resultJson.put("code", result.get("reqCode").equals("0000")?"0" : result.get("reqCode"));
        resultJson.put("msg", result.get("reqMsg"));
        sendWeChatMsg(resultJson.toString());

        return null;
    }
    //贷款验证码验证
    public String  loanRegisterValidatePhoneNo() throws Exception {
        String mobile = getRequest().getParameter("mobile");
        String valiCode = getRequest().getParameter("valiCode");
        //String customerId = getRequest().getParameter("customerId");
        //String terminalTypeId = getRequest().getParameter("terminalTypeId");
        JSONObject result = new JSONObject();
        if (null == mobile) {
            log.warn("发送手机验证码时, 传入参数mobile为空");
            sendWeChatErrorMsg("6001", "mobile");
            return null;
        }

        if (null == valiCode) {
            log.warn("发送手机验证码时, 传入参数valiCode为空");
            sendWeChatErrorMsg("6001", "valiCode");
            return null;
        }

        //验证 手机验证码
        boolean verifi = verifiService.verifiCode(VerifiService.CODETYPE_REGISTER, 1, valiCode, mobile, null);
        if (!verifi) {
            //log.warn("注册时, 验证失败！");
            result.put("code", "2");
            result.put("msg", "验证码错误!");
            sendWeChatMsg(result.toString());
            return null;
        }
        result.put("code", "0");
        result.put("msg", "");
        sendWeChatMsg(result.toString());
        return null;
    }

    //---------------------set get start--------------------
    //---------------------set get end----------------------
}
